﻿using Dapper;
using OMG.Fill.Frunit.Model;
using OMG.Fill.Frunit.Model.Ent;
using OMG.Fill.Frunit.Service;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OMG.Fill.Frunit.Services
{
    /// <summary>
    /// 用户表T_User通用操作类
    /// </summary>
    public class UserServices : Users
    {
        public Pager<List<UserModel>> GetPageList(UserQuery query)
        {
            AreaServices areaService = new AreaServices();
            Pager<List<UserModel>> obj = new Pager<List<UserModel>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            if (!string.IsNullOrEmpty(query.AreaCode))
            {

                if (query.AreaCode.Substring(2, 10).Equals("0000000000"))//省级账号
                {
                    strWhereSql += "and AreaCode like @AreaCode ";
                    paramlist.Add("AreaCode", "%" + query.AreaCode.Substring(0, 2) + "%");
                }
                else if (query.AreaCode.Substring(4, 8).Equals("00000000"))//州级账号
                {
                    strWhereSql += "and AreaCode like @AreaCode ";
                    paramlist.Add("AreaCode", "%" + query.AreaCode.Substring(0, 4) + "%");
                }
                else
                {
                    strWhereSql += "and AreaCode = @AreaCode ";
                    paramlist.Add("AreaCode", query.AreaCode);
                }
            }
            if (!string.IsNullOrEmpty(query.Account))
            {
                strWhereSql += "and Account like @Account ";
                paramlist.Add("Account", "%" + query.Account + "%");
            }
            if (!string.IsNullOrEmpty(query.UserName))
            {
                strWhereSql += "and UserName like @UserName ";
                paramlist.Add("UserName", "%" + query.UserName + "%");
            }
            if (!string.IsNullOrEmpty(query.UserType))
            {
                strWhereSql += "and UserType = @UserType ";
                paramlist.Add("UserType", query.UserType);
            }
            if (!string.IsNullOrEmpty(query.Status))
            {
                strWhereSql += "and Status = @Status ";
                paramlist.Add("Status", query.Status);
            }
            string strFromSql = "from dbo.T_User where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<UserModel>(strSql, paramlist).ToList();
                    foreach (var item in obj.rows)
                    {
                        item.StatusName = string.IsNullOrEmpty(item.Status) ? "" : DataDict.Instance["StatusList"][item.Status];
                        item.UserTypeName = string.IsNullOrEmpty(item.UserType) ? "" : DataDict.Instance["UserType"][item.UserType];
                        item.AreaCodeName = string.IsNullOrEmpty(item.AreaCode)?"": areaService.GetByCodeModel(item.AreaCode).model.Name;
                        item.StrAddTime = item.AddTime == null ? "" : item.AddTime.Value.ToString("yyyy-MM-dd hh:ss:mm");
                        item.StrUpdateTime = item.UpdateTime == null ? "" : item.UpdateTime.Value.ToString("yyyy-MM-dd hh:ss:mm");
                        item.StrLastLoginTime = item.LastLoginTime == null ? "" : item.LastLoginTime.Value.ToString("yyyy-MM-dd hh:ss:mm");
                    }
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取用户表T_User分页列表失败", ex);
                return obj;
            }
        }
        public ResResult<UserModel> LoginUser(string account, string passwords)
        {
            ResResult<UserModel> obj = new ResResult<UserModel>();
            var paramlist = new DynamicParameters();
            passwords = DataSecurity.StringToMD5(passwords.ToString().Trim());
            string strSql = @"select * from dbo.T_User where Account=@Account and Password=@Password";
            string strUpLoginTime = @"UPDATE dbo.T_User set LastLoginTime=@LastLoginTime  where Account=@Account and Password=@Password";
            paramlist.Add("Account", account);
            paramlist.Add("Password", passwords);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var list = dbCon.Query<UserModel>(strSql, paramlist).ToList();
                    if (list.Count == 1)
                    {
                        obj.model = list.FirstOrDefault();
                        UserRoleServices urservice = new UserRoleServices();
                        obj.model.ActionList = urservice.GetUserActionList(obj.model.Id);
                        dbCon.Query<UserModel>(strUpLoginTime, new { Account = account, Password = passwords, LastLoginTime = DateTime.Now }).ToList().FirstOrDefault();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "登录成功!";
                    }
                    else
                    {
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "用户名或密码错误,请检查后再试!";
                    }
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取用户表T_User对象信息失败", ex);
                return obj;
            }
        }
        public override ResResult<int> AddInfo(UserEntity model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_User";
            strSql += "(";
            strSql += "Id,";
            strSql += "Account,";
            strSql += "AreaCode,";
            strSql += "UserName,";
            strSql += "Password,";
            strSql += "UserType,";
            strSql += "Status,";
            strSql += "UninName,";
            strSql += "UnitAddress,";
            strSql += "PostName,";
            strSql += "TelPhone,";
            strSql += "Phone,";
            strSql += "Email,";
            strSql += "Sort,";
            strSql += "QQ,";
            strSql += "Remark,";
            strSql += "AddUser,";
            strSql += "AddTime)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@Account,";
            strSql += "@AreaCode,";
            strSql += "@UserName,";
            strSql += "@Password,";
            strSql += "@UserType,";
            strSql += "@Status,";
            strSql += "@UninName,";
            strSql += "@UnitAddress,";
            strSql += "@PostName,";
            strSql += "@TelPhone,";
            strSql += "@Phone,";
            strSql += "@Email,";
            strSql += "@Sort,";
            strSql += "@QQ,";
            strSql += "@Remark,";
            strSql += "@AddUser,";
            strSql += "@AddTime)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (!CheckAccount(model.Id, model.Account))
                    {
                        model.Id = CustomFun.GetGuid();
                        var paramlist = new DynamicParameters();
                        model.Password = DataSecurity.StringToMD5(CustomFun.GetConfigAppSetting("DefaultPwd"));
                        int result = dbCon.Execute(strSql, model);
                        if (result > 0)
                        {
                            obj.model = result;
                            obj.status = DefaultKey.SuccessResult;
                            obj.message = "添加成功！";
                        }
                        else
                        {
                            obj.model = result;
                            obj.status = DefaultKey.InfoResult;
                            obj.message = "添加失败！数量为:" + result;
                        }
                    }
                    else {
                        obj.model = 0;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "账号重复！";
                    }

                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增用户表T_User对象信息失败", ex);
                return obj;
            }
        }
        public override ResResult<int> UpdateInfo(UserEntity model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_User set ";
            strSql += "Account = @Account,";
            strSql += "AreaCode = @AreaCode,";
            strSql += "UserName = @UserName,";
            strSql += "UserType = @UserType,";
            strSql += "Status = @Status,";
            strSql += "UninName = @UninName,";
            strSql += "UnitAddress = @UnitAddress,";
            strSql += "PostName = @PostName,";
            strSql += "TelPhone = @TelPhone,";
            strSql += "Phone = @Phone,";
            strSql += "Email = @Email,";
            strSql += "Sort = @Sort,";
            strSql += "QQ = @QQ,";
            strSql += "Remark = @Remark,";
            strSql += "UpdateUser = @UpdateUser,";
            strSql += "UpdateTime = @UpdateTime";
            strSql += " where Id = @Id";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (!CheckAccount(model.Id, model.Account))
                    {
                        int result = dbCon.Execute(strSql, model);
                        if (result > 0)
                        {
                            obj.model = result;
                            obj.status = DefaultKey.SuccessResult;
                            obj.message = "更新成功！";
                        }
                        else
                        {
                            obj.model = result;
                            obj.status = DefaultKey.InfoResult;
                            obj.message = "更新失败！数量为:" + result;
                        }
                    }
                    else {
                        obj.model = 0;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "账号重复！";
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;

                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("更新用户表T_User对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 检查账号是否重复
        /// </summary>
        /// <param name="id"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        private bool CheckAccount(string id, string account)
        {
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (id == "0")
                    {
                        string strSql = "select count(1) from dbo.T_User where Account=@Account";
                        if (dbCon.Query<int>(strSql, new { Account = account }).FirstOrDefault() == 1)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        string strSql = "select count(1) from dbo.T_User where Account=@Account and Id!=@Id";
                        if (dbCon.Query<int>(strSql, new { Account = account, Id = id }).FirstOrDefault() == 1)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public ResResult<UserModel> GetInfo(string id)
        {
            AreaServices areaService = new AreaServices();
            ResResult<UserModel> obj = new ResResult<UserModel>();
            string strSql = @"select * from dbo.T_User where Id = @Id";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.model = dbCon.Query<UserModel>(strSql, new { Id = id }).FirstOrDefault();
                    obj.model.Password = "";
                    if (string.IsNullOrEmpty(areaService.GetParentCode(obj.model.AreaCode)))
                    {
                        obj.model.AreaCodes = obj.model.AreaCode;
                    }
                    else
                    {
                        obj.model.AreaCodes = areaService.GetParentCode(obj.model.AreaCode) + "," + obj.model.AreaCode;
                    }
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取用户表T_User对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 密码修改
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <param name="uptype">修改类型：0重置密码，1密码修改</param>
        /// <param name="strpwd"></param>
        /// <returns></returns>
        public ResResult<int> UpdatePassword(string id, int uptype, string strpwd, string stroldpwd)
        {
            ResResult<int> obj = new ResResult<int>();


            string strSql = @"UPDATE dbo.T_User set ";
            strSql += "Password = @Password ";
            strSql += " where Id = @Id";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    if (uptype == 0)
                    {
                        string strPwd = DataSecurity.StringToMD5(CustomFun.GetConfigAppSetting("DefaultPwd"));
                        obj.model = dbCon.Query<int>(strSql, new { Id = id, Password = strPwd }).FirstOrDefault();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "密码重置成功";
                    }
                    else
                    {
                        string strGetUser = "select count(1) from dbo.T_User where Id=@Id and Password=@Password";
                        stroldpwd = DataSecurity.StringToMD5(stroldpwd);
                        //判断原始密码是否正确
                        if (dbCon.Query<int>(strGetUser, new { Id = id, Password = stroldpwd }).FirstOrDefault() == 1)
                        {
                            strpwd = DataSecurity.StringToMD5(strpwd);
                            obj.model = dbCon.Query<int>(strSql, new { Id = id, Password = strpwd }).FirstOrDefault();
                            obj.status = DefaultKey.SuccessResult;
                            obj.message = "密码修改成功!";
                        }
                        else
                        {
                            obj.status = DefaultKey.InfoResult;
                            obj.message = "原始密码错误，请重新输入!";
                        }
                    }
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.message = ex.ToString().Trim();
                obj.status = DefaultKey.ErrorResult;
            }
            return obj;
        }
    }
}